import React, { Component, Fragment } from 'react';
import { Spin } from 'antd';
import PdfJsLib from 'pdfjs-dist';
import ReactPdfJs from './ReactPdfJs';

export default class PDFView extends Component {
  state = {
    numPages: null,
    pdf: null,
  };

  componentDidMount() {
    PdfJsLib.GlobalWorkerOptions.workerSrc = 'pdfjs-dist/lib/pdf.worker.js';
    const { fileUrl } = this.props;
    PdfJsLib.getDocument(fileUrl).then(pdf => {
      this.setState({ pdf, numPages: pdf.numPages });
    });
  }

  render() {
    const { numPages, pdf } = this.state;
    return (
      <Fragment>
        {pdf ? (
          Array.from(new Array(numPages), (el, index) => (
            <ReactPdfJs key={`page_${index + 1}`} pdf={pdf} pageNumber={index + 1} />
          ))
        ) : (
          <Spin
            spinning
            size="large"
            style={{ textAlign: 'center', width: '100%', lineHeight: '4rem' }}
          />
        )}
      </Fragment>
    );
  }
}
